<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import type { FormType } from './categoryDetail'
import { DeleteItem as DeleteItemById, GetCategoryDetail, PostCategoryItem } from '@/api/modules/collection'
import { GetAllData } from '@/api/modules/merchandiseControl'
import { GetOptionData as GetCouponOption } from '@/api/modules/voucher'
import { GetOptionData as GetGivefacialmaskactOption } from '@/api/modules/givefacialmaskact'
import { GetOptionData as GetDrawactOption } from '@/api/modules/drawact'

const router = useRouter()
const route = useRoute()
const id = route.query.id as string

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>(
  {
    collectionId: id,
    tabItem: [
      {
        bannerPic: '',
        sort: 0,
        ctype: 1,
        item: [
          {
            bannerPic: '',
            sort: 0,
            parentId: 0,
            parasId: 0,
            linkUrl: '',
          },
        ],
      },
    ],
  },
)

const optionList = reactive({
  collectionOption: [],
  productOption: [],
  couponOption: [],
  drawactOption: [],
  givefacialmaskactOption: [],
})

const rules = reactive({
  bannerPic: [
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],
  sort: [
    { required: true, message: '请输入自定义排序', trigger: 'blur' },
  ],
  ctype: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],
  // parentId: [
  //   { required: true, message: '请输入分享语', trigger: 'blur' },
  // ],
  linkUrl: [
    { required: true, message: '请输入跳转链接', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, index: number, type: string, indexs?: number) {
  if (type === 'list' && indexs !== undefined) {
    ruleForm.value.tabItem[index].item[indexs].bannerPic = url
  }
  else {
    ruleForm.value.tabItem[index].bannerPic = url
  }
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      // console.log(params)
      PostCategoryItem(params).then((res: any) => {
        if (res.statusCode === 200) {
          ElMessage.success('配置成功')
          router.push({ name: 'categoryIndex' })
        }
        else {
          ElMessage.error(`配置失败。${res.errors}`)
        }
      })
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

// 新增Tab
function AddTab() {
  ruleForm.value.tabItem.push({
    bannerPic: '',
    sort: 0,
    ctype: 1,
    item: [
      {
        bannerPic: '',
        sort: 0,
        parentId: 0,
        parasId: 0,
        linkUrl: '',
      },
    ],
  })
}

function DeleteTab(index: number, id?: number) {
  if (id) {
    DeleteItemById(id).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('删除成功')
        DeleteTab(index)
      }
      else {
        ElMessage.error(`删除失败。${res.errors}`)
      }
    })
  }
  else {
    ruleForm.value.tabItem.splice(index, 1)
  }
}

// 新增卡片
function AddItem(index: number) {
  if (ruleForm.value.tabItem[index].item) {
    ruleForm.value.tabItem[index].item.push({
      bannerPic: '',
      sort: 0,
      parentId: 0,
      parasId: 0,
      linkUrl: '',
    })
  }
  else {
    ruleForm.value.tabItem[index].item = [{
      bannerPic: '',
      sort: 0,
      parentId: 0,
      parasId: 0,
      linkUrl: '',
    }]
  }
  // console.log(ruleForm.value)
}
// 删除卡片
function DeleteItem(index: number, indexs: number, id?: number) {
  if (id) {
    DeleteItemById(id).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('删除成功')
        DeleteItem(index, indexs)
      }
      else {
        ElMessage.error(`删除失败。${res.errors}`)
      }
    })
    ruleForm.value.tabItem[index].item.splice(indexs, 1)
  }
  else {
    ruleForm.value.tabItem[index].item.splice(indexs, 1)
  }
}

onMounted(async () => {
  GetCategoryDetail(id).then((res: any) => {
    if (res.statusCode === 200) {
      ruleForm.value = res.data
      // console.log(ruleForm.value)
      if (ruleForm.value.tabItem.length === 0) {
        AddTab()
      }
    }
  })
  // 获取选择器选项
  // const collectionId: any = await GetCollectionId()
  // if (collectionId.statusCode === 200) {
  //   optionList.collectionOption = collectionId.data
  // }
  const productParams = qs.stringify({ ProductName: '', IsActive: true })
  const productData: any = await GetAllData(productParams)
  if (productData.statusCode === 200) {
    optionList.productOption = productData.data.map((item: any) => {
      return {
        label: item.productName,
        value: item.productId,
      }
    })
  }
  const couponData: any = await GetCouponOption()
  if (couponData.statusCode === 200) {
    optionList.couponOption = couponData.data.map((item: any) => {
      return {
        label: item.name,
        value: item.id,
      }
    })
  }
  const givefacialmaskactData: any = await GetGivefacialmaskactOption()
  if (givefacialmaskactData.statusCode === 200) {
    optionList.givefacialmaskactOption = givefacialmaskactData.data.map((item: any) => {
      return {
        label: item.title,
        value: item.id,
      }
    })
  }
  const drawactData: any = await GetDrawactOption()
  if (drawactData.statusCode === 200) {
    optionList.drawactOption = drawactData.data.map((item: any) => {
      return {
        label: item.drawId,
        value: item.drawId,
      }
    })
  }
})
</script>

<template>
  <div>
    <PageHeader title="配置" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain v-for="(item, index) in ruleForm.tabItem" :key="item.id">
        <template #title>
          {{ `模块${index + 1}` }}
          <el-button v-if="!(ruleForm.tabItem.length === 1)" type="danger" @click="DeleteTab(index, item.id)">
            删除
          </el-button>
        </template>
        <ElRow :gutter="20">
          <ElCol :md="12">
            <ElFormItem label="图片">
              <ImageUpload
                width="auto" height="120" :size="5" :url="item.bannerPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, index, 'notList')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="6">
            <ElFormItem label="自定义排序">
              <el-input v-model="item.sort" placeholder="请输入自定义排序" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="6">
            <ElFormItem label="类型">
              <el-radio-group v-model="item.ctype">
                <el-radio :value="1">
                  商品
                </el-radio>
                <el-radio :value="3">
                  面膜活动
                </el-radio>
                <el-radio :value="2">
                  券
                </el-radio>
                <el-radio :value="4">
                  抽奖活动
                </el-radio>
              </el-radio-group>
            </elformitem>
          </ElCol>
          <ElCol v-for="(items, indexs) in item.item" :key="items.id" :md="8" class="mb-5">
            <el-card shadow="hover">
              <el-scrollbar height="440px" :noresize="true">
                <div class="card-box">
                  <ElFormItem label="图片" style="grid-column: 1 / 3;">
                    <ImageUpload
                      height="150" width="auto" :size="1" :url="items.bannerPic" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, index, 'list', indexs)"
                    />
                  </ElFormItem>
                  <!-- <ElFormItem label="归属的区域分类ID">
                    <el-select v-model="items.parentId" placeholder="请选择归属的区域分类ID">
                      <el-option v-for="collectionId in (optionList.collectionOption as any)" :key="collectionId.collectionId" :label="collectionId.collectionId" :value="collectionId.collectionId" />
                    </el-select>
                  </elformitem> -->
                  <ElFormItem label="跳转链接" style="grid-column: 1 / 3;">
                    <el-input v-model="items.linkUrl" placeholder="请输入跳转链接" style="max-width: 100%;" />
                  </ElFormItem>
                  <ElFormItem label="配置">
                    <el-select v-if="item.ctype === 1" v-model="items.parasId" placeholder="请选择商品" style="max-width: 450px;" filterable>
                      <!-- 商品 -->
                      <el-option v-for="product in (optionList.productOption as any)" :key="product.value" :label="`${product.value}-${product.label}`" :value="product.value" />
                    </el-select>
                    <!-- 券 -->
                    <el-select v-if="item.ctype === 2" v-model="items.parasId" placeholder="请选择券" filterable>
                      <el-option v-for="coupon in (optionList.couponOption as any)" :key="coupon.value" :label="`${coupon.value}-${coupon.label}`" :value="coupon.value" />
                    </el-select>
                    <el-select v-if="item.ctype === 3" v-model="items.parasId" placeholder="请选择活动" filterable>
                      <!-- 面膜 -->
                      <el-option v-for="givefacialmaskact in (optionList.givefacialmaskactOption as any)" :key="givefacialmaskact.value" :label="givefacialmaskact.label" :value="givefacialmaskact.value" />
                    </el-select>
                    <el-select v-if="item.ctype === 4" v-model="items.parasId" placeholder="请选择活动" filterable>
                      <!-- 抽奖 -->
                      <el-option v-for="drawact in (optionList.drawactOption as any)" :key="drawact.value" :label="drawact.label" :value="drawact.value" />
                    </el-select>
                  </elformitem>
                  <ElFormItem label="自定义排序">
                    <el-input v-model="items.sort" placeholder="请输入自定义排序" type="number" />
                  </ElFormItem>
                </div>
              </el-scrollbar>
              <template #footer>
                <div class="flex justify-between">
                  <el-button type="success" @click="AddItem(index)">
                    新增
                  </el-button>
                  <el-button type="danger" :disabled="item.item.length === 1" @click="DeleteItem(index, indexs, items.id)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-card>
          </ElCol>
          <ElCol :md="24">
            <el-button v-if="ruleForm.tabItem.length - 1 === index" type="success" @click="AddTab">
              新增模块
            </el-button>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
